package com.example.auth3.config;

import com.example.auth3.mapper.SPrivilegeUserMapper;
import com.example.auth3.util.DfUtils;
import com.example.util.model.PrivilegeUser;
import com.example.util.model.Role;
import com.example.util.model.SecurityLogin;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
/**
 * 实现了查询用户信息的接口 确定按照我们的想法查询用户信息
 * @author shangSshang
 * 2018.12.21 12:00:03
 */
@Slf4j
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    private   static final  Logger logger= LoggerFactory.getLogger(MyUserDetailsService.class);
    @Autowired
    private SPrivilegeUserMapper sPrivilegeUserMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SecurityLogin user = sPrivilegeUserMapper.findUserInfsByLoginName(s);
        if(DfUtils.isNotBank(user) && DfUtils.isNotBank(user.getId())){
            List<Role> lr =sPrivilegeUserMapper.getRolesByUserId(user.getId());
            user.setLr(lr);
        }else{
                throw new UsernameNotFoundException("用户名："+ user + "不存在！");
        }
        logger.info("认证用户: "+user);

        Collection<SimpleGrantedAuthority> collection = new HashSet<SimpleGrantedAuthority>();
        Iterator<Role> iterator =  user.getLr().iterator();
        while (iterator.hasNext()){
            collection.add(new SimpleGrantedAuthority(iterator.next().getRoleCode()));
        }

//        return new org.springframework.security.core.userdetails.User(s,user.getLoginPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
        return new org.springframework.security.core.userdetails.User(s,user.getLoginPassword(),collection);
    }


}
